package com.amazon.trietree.db;

import java.sql.*;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: Tylaar
 * Date: 11/8/12
 * Time: 4:45 PM
 * Company: Amazon.com
 */
public class PostgreUtils {
    private String dbLocation;
    private String username;
    private String password;
    private Connection conn;

    public String getDbLocation() {
        return dbLocation;
    }

    public void setDbLocation(String dbLocation) {
        this.dbLocation = dbLocation;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Connection getConnection() throws SQLException {
        if(this.conn == null){
            Properties props = new Properties();
            props.setProperty("user",username);
            props.setProperty("password",password);
            //props.setProperty("ssl","true");
            this.conn = DriverManager.getConnection(dbLocation, props);
        }
        return this.conn;
    }

    public void closeConnection()throws Exception{
        this.conn.close();
    }

    public Long getNextVal(){
        try {
            Connection conn = getConnection();
            String sql = "select nextval('paxos_seq')";
            PreparedStatement prpState = conn.prepareStatement(sql);
            ResultSet rs = prpState.executeQuery();
            if(rs.next()){
                return rs.getLong(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return -1l;
    }
}
